﻿using NB.MGJ.Common.MVC;
using NB.MGJ.Model;
using NB.MGJ.Model.OriginsEntity;
using NB.MGJ.Service;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ThoughtWorks.QRCode.Codec;
using WxPayAPI;

namespace NB.MGJ.Web.Controllers
{
    //支付控制器
    public class PaymentController : BaseController
    {

        #region 支付
        public ActionResult NativePayPage(string fee,string reamk)
        {
            int temp =int.Parse(fee);
            string url2 = GetPayUrl("7788", temp*100);
            ViewBag.ImageUrl = HttpUtility.UrlEncode(url2);
            ViewBag.reamk = reamk;
            return View();
        }
      
        /**
        * 生成直接支付url，支付url有效期为2小时,模式二
        * @param productId 商品ID
        * @return 模式二URL
        */
        public string GetPayUrl(string productId, int fee)
        {
            WxPayData data = new WxPayData();
            data.SetValue("body", "金额充值");//商品描述
            data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//随机字符串

            data.SetValue("total_fee", fee);//总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
            data.SetValue("trade_type", "NATIVE");//交易类型
            data.SetValue("product_id", productId);//商品ID

            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
            string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
            string teadeno = data.GetValue("out_trade_no").ToString();
            //string fee = data.GetValue("total_fee").ToString();
            ViewData["Trade_no"] = teadeno;
            ViewBag.fee = fee;
            //附加数据data.SetValue("attach", "附加信息,用于后台或者存入数据库,做自己的判断");
            //商品标记data.SetValue("goods_tag", "商品的备忘,可以自定义");
            return url;
        }

        public ActionResult MakeQRCode(string data)
        {
            //  if (!string.IsNullOrEmpty(Request.QueryString["data"]))
            //   {
            // string str = data.ToString();

            //初始化二维码生成工具
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            qrCodeEncoder.QRCodeVersion = 0;
            qrCodeEncoder.QRCodeScale = 4;

            //将字符串生成二维码图片
            Bitmap image = qrCodeEncoder.Encode(data, Encoding.Default);

            //保存为PNG到内存流  
            MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);

            //输出二维码图片
            Response.BinaryWrite(ms.GetBuffer());
            Response.End();
            //   }
            return View();
        }

        #endregion

        #region 支付回调
        public ActionResult ResultNotifyPage()
        {
            string strData = ProcessNotify();
            Response.Write(strData);
            return View();

        }

        public string ProcessNotify()
        {
            WxPayData notifyData = GetNotifyData();

            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                return res.ToXml();
            }

            string transaction_id = notifyData.GetValue("transaction_id").ToString();

            //查询订单，判断订单真实性
            if (!QueryOrder(transaction_id))
            {
                //若订单查询失败，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                return res.ToXml();
            }
            //查询订单成功
            else
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
                string strXml = res.ToXml();
                //  FileLog.WriteLog(strXml);
                return res.ToXml();//如果我们走到这一步了，那就代表，用户已经支付成功了，所以，该干嘛干嘛了。
                //   return "SUCCESS";
            }
        }
        /// <summary>
        /// 接收从微信支付后台发送过来的数据并验证签名
        /// </summary>
        /// <returns>微信支付后台返回的数据</returns>
        public WxPayData GetNotifyData()
        {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = Request.InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();

            Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString());

            //转换数据格式并验证签名
            WxPayData data = new WxPayData();
            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若签名错误，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
                return res;
            }

            return data;
        }


        private bool QueryOrder(string transaction_id)
        {
            WxPayData req = new WxPayData();
            req.SetValue("transaction_id", transaction_id);
            WxPayData res = WxPayApi.OrderQuery(req);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 微信扫码支付 查询支付结果 每2秒循环一次
        /// </summary>
        /// <param name="id">商品订单id</param>
        /// <param name="outid">商户订单id</param>
        /// <returns>支付结果</returns>
        public JsonResult ResultPayWX(string id, string outid,string remark )
        {
            var result = OrderQuery.Run(id, outid);//获取xml
            string str = result;
            if (str[str.Length - 1] == ',')
            {
                str = str.Substring(0, str.Length - 1);
            }
            string[] strarr = str.Split(',');//转化为数组，去掉逗号分割
            string _s = strarr[strarr.Length - 1];
            string soutid = "out_trade_no=" + outid;
            if (_s == "trade_state_desc=订单未支付")
            {
                return Json(_s);
            }
            else if (strarr[9] == soutid)
            {
                organization_PaymentInfo model=new organization_PaymentInfo();
                model.remark = remark;
                int money = Convert.ToInt32(strarr[15].Split('=')[1])/100;//截取等于号后面的价格
                model.PeyType = 1;
                model.out_trade_no = strarr[9].Split('=')[1];
                model.transaction_id = strarr[18].Split('=')[1];
                model.openid = strarr[8].Split('=')[1];
                string date =  strarr[14].Split('=')[1] ;
                string yyyy = date.Substring(0,4);
                string MM = date.Substring(4,2);
                string dd = date.Substring(6,2);
                string HH = date.Substring(8,2);
                string mm = date.Substring(10, 2);
                string ss = date.Substring(12, 2);
                model.DealMoney = money;
                model.DealTime = Convert.ToDateTime(yyyy+"-"+MM+"-"+dd+" "+HH+":"+mm+":"+ss);
                AddFinanciallog(model);
                ManagerService man = new ManagerService();
                Organization_Enterprise e = new Organization_Enterprise();
                e.ID = LogOnUser.EnterpriseId;
 
                man.updEnterpriseService(e);
                return Json(strarr);

                //AddFinanciallog();//支付成功进行数据库操作
            }
            else
            {
                return Json("");
            }
        }  
        PaymentService _payService = new PaymentService();
        public int AddFinanciallog(organization_PaymentInfo model)
        {
            model.EnterpriseID = LogOnUser.EnterpriseId;
            model.LoginName =LogOnUser.LoginName;
            model.IsBill = 0;
        
            return _payService.AddTradingrecord(model);
        }
        #endregion

        PaymentService pay=new PaymentService();

        #region 交易记录列表显示
        public JsonResult PagePaymentInfoList(string searchKey,int type,int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            string where =" 1=1 "; 
            if (type!=0)
	        {
                where += " and PeyType="+type;
            }
            if (searchKey!="")
	        {
		 where+=" and (  LoginName like '%"+searchKey+"%' or transaction_id like '%"+searchKey+"%' or out_trade_no like '%"+searchKey+"%'  )  and PeyType="+type;
            }
            pm.StrCondition = where;
            //  pm.StrCondition = where != null ? " name like '%" + where + "%' " : where;
            var model = pay.GetPaymentInfoTable(ref pm);
            return Json(model);

        }
        #endregion

        #region 微信红包

        #endregion

        #region 红包回调
        public ActionResult RedBackResult() 
        {
            return View();
        }
        #endregion
    }
}